package com.tsd.jxc.fin.service.impl;

import com.tsd.base.service.BaseCodeRuleService;
import com.tsd.common.vo.BatchDeleteLogicVo;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.service.GetDuplicatedObj;
import com.tsd.core.utils.DoubleUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.config.JxcCodeRuleConstants;
import com.tsd.jxc.fin.FinanceConstants;
import com.tsd.jxc.fin.dao.JxcFinanceAccountDetailMapper;
import com.tsd.jxc.fin.dao.JxcFinanceAccountMapper;
import com.tsd.jxc.fin.entity.JxcFinanceAccountDetail;
import com.tsd.jxc.fin.entity.JxcFinanceAccountDetailExt;
import com.tsd.jxc.fin.entity.JxcFinanceAccountExt;
import com.tsd.jxc.fin.job.JxcFinanceJob;
import com.tsd.jxc.fin.service.JxcFinanceAccountDetailService;
import com.tsd.jxc.fin.service.JxcFinanceAccountService;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.entity.SysUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 描述：JxcFinanceAccountDetail 服务实现层
 *
 * @author Hillpool
 * @date 2022/09/01 16:14:21
 */
@Service
public class JxcFinanceAccountDetailServiceImpl extends BaseServiceImpl implements JxcFinanceAccountDetailService, GetDuplicatedObj {

    @Resource
    private JxcFinanceAccountDetailMapper jxcFinanceAccountDetailMapper;
    @Resource
    private JxcFinanceAccountMapper jxcFinanceAccountMapper;
    @Resource
    private JxcFinanceAccountService jxcFinanceAccountService;
    @Resource
    private BaseCodeRuleService baseCodeRuleService;
    @Resource
    private JxcFinanceJob jxcFinanceJob;

    @Override
    public JxcFinanceAccountDetail getJxcFinanceAccountDetailById(Long id) throws Exception {
        return jxcFinanceAccountDetailMapper.selectByPrimaryKey(id);
    }

    @Override
    public JxcFinanceAccountDetailExt queryBySid(String sid) throws Exception {
        return jxcFinanceAccountDetailMapper.selectBySid(sid);
    }

    @Override
    public void deleteJxcFinanceAccountDetails(List<String> list, SysUser opUser) throws Exception {
        if (HlpUtils.isEmptyList(list)) {
            return;
        }
        JxcFinanceAccountDetailExt params = new JxcFinanceAccountDetailExt();
        params.setDr(0);
        params.setSid_list(list);
        List<JxcFinanceAccountDetailExt> detailExtList = jxcFinanceAccountDetailMapper.selectByEntity(params);
        if (HlpUtils.isEmptyList(detailExtList)) {
            return;
        }

        BatchDeleteLogicVo logicVo = new BatchDeleteLogicVo(opUser);
        logicVo.setSidList(list);
        jxcFinanceAccountDetailMapper.deleteLogicBySidList(logicVo);

        // 添加队列
        for (JxcFinanceAccountDetailExt detailExt : detailExtList) {
            jxcFinanceJob.addJxcFinanceQue(FinanceConstants.QUEUE_OP_DELETE, FinanceConstants.BIZ_NAME_FINANCE, "updateFinanceAmount", detailExt.getId(), opUser);
        }
    }

    @Override
    public boolean isDuplicated(Object obj, String code) {
        if (obj == null) {
            return false;
        }
        JxcFinanceAccountDetailExt orderExt = (JxcFinanceAccountDetailExt) obj;
        orderExt.setCode(code);
        return jxcFinanceAccountDetailMapper.selectDuplicatedCode(orderExt) != null;
    }

    @Override
    public void saveJxcFinanceAccountDetail(JxcFinanceAccountDetailExt record, SysUser opUser) throws Exception {
        String dataSource = DataSourceContextHolder.getDataSourceType();
        if (HlpUtils.isEmpty(record.getId())) {
            super.checkEmpty(record.getType(), "请提供参数：type");
            super.checkEmpty(record.getRelated_party_sid(), "请提供参数：related_party_sid");
            List<JxcFinanceAccountExt> accountExtList = jxcFinanceAccountMapper.selectValidByPartyList(Collections.singletonList(record.getRelated_party_sid()));
            double remainAmount = 0D;
            if (!HlpUtils.isEmptyList(accountExtList)) {
                remainAmount = accountExtList.get(0).getAmount().doubleValue();
            } else {
                jxcFinanceAccountService.initData(record.getRelated_party_sid(), opUser);
            }
            if (FinanceConstants.OP_ADD.equals(FinanceConstants.getAccountTypeOp(dataSource, record.getBill_type()))) {
                remainAmount = DoubleUtil.add(remainAmount, FinanceConstants.getAmount(record));
            } else {
                remainAmount = DoubleUtil.sub(remainAmount, FinanceConstants.getAmount(record));
            }
            record.setRemain_amount(BigDecimal.valueOf(remainAmount));
            if (!HlpUtils.isEmpty(record.getCode())) {
                //如果是手动设置了编号，则检查是否有相同的，有的话，置空后重新生成
                JxcFinanceAccountDetailExt same = jxcFinanceAccountDetailMapper.selectDuplicatedCode(record);
                if (same != null) {
                    record.setCode(null);
                }
            }
            if (HlpUtils.isEmpty(record.getCode())) {
                String genCode = baseCodeRuleService.genCode(record.getRelated_party_sid(), JxcCodeRuleConstants.TYPE_JXC_FINANCE_ACCOUNT, JxcCodeRuleConstants.TYPE_NAME_JXC_FINANCE_ACCOUNT, opUser, record.getCode(), record, this);
                record.setCode(genCode);
            }
            if (HlpUtils.isEmpty(record.getRemain_amount())) {
                record.setRemain_amount(BigDecimal.ZERO);
            }
            super.autoInjectBaseData(record, opUser, this.TYPE_CREATE);
            jxcFinanceAccountDetailMapper.insertSelective(record);

            // 添加队列
            jxcFinanceJob.addJxcFinanceQue(FinanceConstants.QUEUE_OP_INSERT, FinanceConstants.BIZ_NAME_FINANCE, "updateFinanceAmount", record.getId(), opUser);
        } else {
            JxcFinanceAccountDetailExt same = jxcFinanceAccountDetailMapper.selectDuplicatedCode(record);
            if (same != null) {
                throw new HlpException("已存在相同编号的记录");
            }
            super.autoInjectBaseData(record, opUser, this.TYPE_UPDATE);
            jxcFinanceAccountDetailMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public List<JxcFinanceAccountDetailExt> findJxcFinanceAccountDetails(Map<String, Object> params, PageBean page) throws Exception {
        return jxcFinanceAccountDetailMapper.selectByPage(params, page);
    }

    @Override
    public List<JxcFinanceAccountDetailExt> findJxcFinanceAccountDetails(Map<String, Object> params) throws Exception {
        return jxcFinanceAccountDetailMapper.selectByParams(params);
    }

    @Override
    public List<JxcFinanceAccountDetailExt> queryJxcFinanceCheck(Map<String, Object> params, PageBean page) {
        return jxcFinanceAccountDetailMapper.select4CheckByPage(params, page);
    }
}
